local Config = require("Config")
local Msg = require("core.Msg")
local MiddleLogic = require("middle.MiddleLogic")
local MPacketDefine = require("middle.MPacketDefine")
local MiddleOpenDB = require("middle.MiddleOpenDB")

function G2M_MIDDLE_CHAT(fdTemp, msg)
	if not Config.IS_MIDDLE then return end

	-- 收到聊天消息 先在跨服广播
	local msgChat = Msg.gc.GC_CHAT_MIDDLE
	msgChat.msg_type = msg.type
	msgChat.role_name = msg.roleName
	msgChat.blue = msg.blue
	msgChat.msg = msg.content
	Msg.sendAll(msgChat)
	
	syncChatFromMiddle(fdTemp, msg.svrIndex, msg.type, msg.roleName, msg.content, msg.blue)
end

function M2G_MIDDLE_CHAT(fd, msg)
	if Config.IS_MIDDLE == true then return end

	if msg.roleName == "" then
		-- 副本招募 要判断本服开了跨服没有 没有开的话就不广播了
		if MiddleOpenDB.isMiddleOpen() ~= true then
			return
		end
	end

	-- 收到跨服的同步 世界广播
	local msgChat = Msg.gc.GC_CHAT_MIDDLE
	msgChat.msg_type = msg.type
	msgChat.role_name = msg.roleName
	msgChat.blue = msg.blue
	msgChat.msg = msg.content
	Msg.sendAll(msgChat)
end

function sendChat2Middle(type, roleName, content, blue)
	if _G.msg_middle_parse.check_connect() == true then
		_G.msg_middle_parse.writebegin(0)
		_G.msg_middle_parse.writeint(MPacketDefine.G2M_MIDDLE_CHAT)
		_G.msg_middle_parse.writeint(Config.SVR_INDEX)
		_G.msg_middle_parse.writeint(type)
		_G.msg_middle_parse.writestring(roleName)
	  _G.msg_middle_parse.writestring(blue)		
		_G.msg_middle_parse.writestring(content)		
		_G.msg_middle_parse.writeend()
	end
end

-- 同步给其他服
function syncChatFromMiddle(fdTemp, svrIndex, type, roleName, content, blue)
	for fd, v in pairs(MiddleLogic.FD_2_SVNINDEX) do
		if fd ~= fdTemp then
			_G.msg_middle_parse.writebegin(fd)
			_G.msg_middle_parse.writeint(MPacketDefine.M2G_MIDDLE_CHAT)
			_G.msg_middle_parse.writeint(svrIndex)
			_G.msg_middle_parse.writeint(type)              
			_G.msg_middle_parse.writestring(roleName)    
			_G.msg_middle_parse.writestring(blue) 
			_G.msg_middle_parse.writestring(content)    
			_G.msg_middle_parse.writeend()
		end
	end
end